/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vista.planificacion;

import controlador.planificacion.GestorPlanificacionHerramientas;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.TareaPlanificacion;
import util.NTupla;
import util.TablaUtil;

/**
 *
 * @author Administrador
 */
public class PlanificacionHerramientas extends javax.swing.JPanel {

    private GestorPlanificacionHerramientas gestor;
    /**
     * Creates new form PlanificacionHerramientas
     */
    public PlanificacionHerramientas(GestorPlanificacionHerramientas gestor) {
        initComponents();
        this.gestor =  gestor;
        this.gestor.setPantalla(this);
        cargarDatos();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tblHerramientas = new javax.swing.JTable();
        btnEliminar = new javax.swing.JButton();
        txtHorasTotal = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        tblHerramientas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Herramienta", "Horas Asignadas"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblHerramientas.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tblHerramientas);

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/iconos/var/16x16/delete.png"))); // NOI18N
        btnEliminar.setText("Quitar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        txtHorasTotal.setEditable(false);
        txtHorasTotal.setText("$ -");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel1.setText("Total de Horas Asignadas:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtHorasTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtHorasTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEliminar)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        
        TareaPlanificacion tarea = gestor.getTareaActual();
        
        int row = tblHerramientas.getSelectedRow();
        if(row>=0 && tarea!=null)
        {
            NTupla nt = (NTupla)tblHerramientas.getModel().getValueAt(row,0); 
            eliminarAsignacionHerramienta(nt, this);
        }
        else
        {
            JOptionPane.showMessageDialog(new JFrame(),"Seleccione una fila para eliminar","Atencion!",JOptionPane.WARNING_MESSAGE);
        }
        
    }//GEN-LAST:event_btnEliminarActionPerformed

    public boolean eliminarAsignacionHerramienta(NTupla nt, JComponent panel)
    {
        TareaPlanificacion tarea = gestor.getTareaActual();
        if(nt!=null) {
                System.out.println("NT:"+nt.getNombre()+"/"+nt.getId());
                StringBuilder msg = new StringBuilder("<HTML>");
                msg.append("Está a punto de eliminar la asignación de");
                msg.append(" <b>");
                msg.append("<span color=\"#FF0000\">");
                    String[] data = (String[]) nt.getData();
                    msg.append(data[0]);
                msg.append(" Hs.</span>");
                msg.append("</b> ");
                msg.append(" de la herramienta:");
                msg.append("<br/>");
                msg.append("<b>");
                msg.append(nt.getNombre());
                msg.append("</b>");
                msg.append("<br/>");
                msg.append("de la tarea:");
                msg.append("<br/>");
                msg.append("<b>");
                msg.append(tarea.getNombre());
                msg.append("</b>");
                
                Object[] options = {"Cancelar","Eliminar Asignación + Gastos Asociados","Eliminar Asignación"};
                int n = JOptionPane.showInternalOptionDialog(panel,msg.toString(),"Atencion!",JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,null,options,options[1]);            
                System.out.println("SELECCIONO: "+n);
                boolean exito=false;
                boolean exito2=false;
                switch(n)
                {
                    case 0:
                       // Cancelar ..nadaremos
                       break;
                    case 1:
                        // Elimino asignación + Gastos
                        exito = gestor.eliminarAsignación(nt.getId(), true);
                        mostrarMensajeExitoEliminacion(data[0],nt.getNombre(),exito);
                        cargarDatos();
                        break;
                    case 2: 
                        // Elimino solo la asignacion
                        exito2 = gestor.eliminarAsignación(nt.getId(), false);
                        mostrarMensajeExitoEliminacion(data[0],nt.getNombre(),exito2);
                        cargarDatos();
                        break;
                    default:
                        // No ocurre
                }
                return (exito||exito2);
                
            }
        else {
            return false;
        }
    }
    
    private void mostrarMensajeExitoEliminacion(String horas, String herramienta, boolean exito)
    {
        StringBuilder msg = new StringBuilder("<HTML>");
        if(exito)
        {
            msg.append("<span color=\"#009900\">");
            msg.append("Se eliminó correctamente la asignación de");
            msg.append("</span>");            
        }
        else
        {
            msg.append("<span color=\"#FF0000\">");
            msg.append("Se detecto un problema al eliminar la asignación de " );
            msg.append("</span>");
        }
        msg.append("<br/>");
        msg.append("<b>");
        msg.append(horas);
        msg.append(" Hs.</b>");
        msg.append(" de la herramienta ");
        msg.append("<br/>");
        msg.append("<b>");
        msg.append(herramienta);
        msg.append("</b>");
        
        if(exito)
        {
            JOptionPane.showMessageDialog(new JFrame(),msg.toString(),"Atención!",JOptionPane.INFORMATION_MESSAGE);
        }
        else
        {
            JOptionPane.showMessageDialog(new JFrame(),msg.toString(),"Error!",JOptionPane.ERROR_MESSAGE);
        }
        
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEliminar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblHerramientas;
    private javax.swing.JTextField txtHorasTotal;
    // End of variables declaration//GEN-END:variables

    private void cargarDatos() {
        
        DefaultTableModel modelo = (DefaultTableModel)tblHerramientas.getModel();
        TablaUtil.vaciarDefaultTableModel(modelo);
        
        int total = 0;
        
        ArrayList<NTupla> filas = gestor.cargarDatos();
        for (int i = 0; i < filas.size(); i++) {
            NTupla nTupla = filas.get(i);
            String[] data = (String[]) nTupla.getData();
            
            Object[] fila = new Object[2];
            fila[0] = nTupla;
            fila[1] = data[0]+" Hs.";
            
            // Acumulo
            int subTotal = Integer.parseInt(data[0]);
            total += subTotal;
            modelo.addRow(fila);
        }
        
        txtHorasTotal.setText(total+" Hs.");
        
    }
}
